package com.dx_society.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dx_society.domain.Societies;
import com.dx_society.domain.SocietiesMember;
import com.dx_society.dto.Result;
import com.dx_society.mapper.SocietiesMapper;
import com.dx_society.service.MessageService;
import com.dx_society.service.SocietiesMemberService;
import com.dx_society.mapper.SocietiesMemberMapper;
import com.dx_society.service.SocietiesService;
import com.dx_society.utils.UserHolder;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.dx_society.utils.RedisConstants.SOCIETIES_LIST_TTL;

/**
 * @author 韶光善良君
 * @description 针对表【dx_societies_member(社团成员关系表)】的数据库操作Service实现
 * @createDate 2024-07-01 10:15:25
 */
@Service
public class SocietiesMemberServiceImpl extends ServiceImpl<SocietiesMemberMapper, SocietiesMember>
        implements SocietiesMemberService {
    @Resource
    private SocietiesMapper societiesMapper;
    @Resource
    private SocietiesService societiesService;
    @Resource
    private MessageService messageService;
    @Override
    public Result leaveSocieties(Long id, String leaveReason) {
        Long userId;
        try {
            userId = UserHolder.getUser().getUserid();
        } catch (Exception e) {
            return Result.fail("用户未登录");
        }
        QueryWrapper<SocietiesMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("societies_id", id);
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("state", 1);
        SocietiesMember societiesMember = getOne(queryWrapper);
        // 检查是否存在
        if (societiesMember != null) {
            // state改为2，补充退部理由
            societiesMember.setState(2);
            societiesMember.setLeaveReason(leaveReason);
            update(societiesMember, queryWrapper);
            return Result.ok("退部申请已提交，请等待部长审批");
        } else {
            return Result.fail("您不是该社团成员");
        }
    }

    @Override
    public Result joinSocieties(Long id, String joinReason) {
        Long userId;
        try {
            userId = UserHolder.getUser().getUserid();
        } catch (Exception e) {
            return Result.fail("用户未登录");
        }
        QueryWrapper<SocietiesMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("societies_id", id);
        queryWrapper.eq("user_id", userId);
        SocietiesMember societiesMember = getOne(queryWrapper);
        // 检查是否存在
        if (societiesMember == null) {
            // 不存在，创建新的关系，state改为0，填写入部原因
            societiesMember = new SocietiesMember();
            societiesMember.setSocietiesId(id);
            String so_name = societiesMapper.selectById(id).getSoName();
            societiesMember.setSocietiesName(so_name);
            societiesMember.setUsername(UserHolder.getUser().getUsername());
            societiesMember.setUserId(userId);
            societiesMember.setState(0);
            societiesMember.setJoinReason(joinReason);
            save(societiesMember);
            return Result.ok("入部申请已提交，请等待部长审批");
        } else if (societiesMember.getState() == 1) {
            return Result.fail("您已经是该社团成员");
        } else if (societiesMember.getState() == 2) {
            return Result.fail("您已提交退部申请，请等待部长审批");
        } else if (societiesMember.getState() == 0) {
            return Result.fail("您已提交入部申请，请等待部长审批");
        } else {
            return Result.fail("未知错误");
        }
    }

    @Override
    public Result queryMySocietyMemberList() {
        Societies soMasterId = (Societies) societiesService.querySocietiesDetailByMasterId().getData();
        List<SocietiesMember> societiesMembers = queryMemberListWithSoId(soMasterId.getSoId(), 1);
        if (societiesMembers.isEmpty()) {
            return Result.fail("暂无成员信息");
        }
        return Result.ok(societiesMembers);
    }


    /**
     * 根据so_id查询成员列表
     *
     * @param id    社团id
     * @param state 加入状态
     * @return 成员列表
     */
    @Override
    public List<SocietiesMember> queryMemberListWithSoId(Long id, Integer state) {
        List<SocietiesMember> list = query().eq("societies_id", id).eq("state", state).list();
        return list;
    }

    @Override
    public Result queryMySocietyJoinList() {
        Societies soMasterId = (Societies) societiesService.querySocietiesDetailByMasterId().getData();
        List<SocietiesMember> societiesMembers = queryMemberListWithSoId(soMasterId.getSoId(), 0);
        if (societiesMembers.isEmpty()) {
            return Result.fail("暂无成员信息");
        }
        return Result.ok(societiesMembers);
    }

    @Override
    public Result queryMySocietyLeaveList() {
        Societies soMasterId = (Societies) societiesService.querySocietiesDetailByMasterId().getData();
        List<SocietiesMember> societiesMembers = queryMemberListWithSoId(soMasterId.getSoId(), 2);
        if (societiesMembers.isEmpty()) {
            return Result.fail("暂无成员信息");
        }
        return Result.ok(societiesMembers);
    }

    @Override
    public Result agreeJoin(Long id, Boolean agree) {
        Societies soMasterId = (Societies) societiesService.querySocietiesDetailByMasterId().getData();
        SocietiesMember old = getById(id);
        if (Objects.equals(old.getSocietiesId(), soMasterId.getSoId()) && old.getState() == 0) {
            if (agree) {
                // 同意入部
                old.setState(1);
                updateById(old);
                societiesService.saveSocieties2Redis(SOCIETIES_LIST_TTL);
                messageService.sendMessage(old.getUserId(), "入部申请已通过");
                return Result.ok("入部申请已通过");
            } else {
                removeById(id);
                messageService.sendMessage(old.getUserId(), "入部申请未通过");
                return Result.ok("入部申请已拒绝");
            }
        }else {
            return Result.fail("该申请不存在");
        }

    }

    @Override
    public Result agreeLeave(Long id, Boolean agree) {
        Societies soMasterId = (Societies) societiesService.querySocietiesDetailByMasterId().getData();
        SocietiesMember old = getById(id);
        if (Objects.equals(old.getSocietiesId(), soMasterId.getSoId()) && old.getState() == 2) {
            if (agree) {
                // 同意退部
                removeById(id);
                societiesService.saveSocieties2Redis(SOCIETIES_LIST_TTL);
                messageService.sendMessage(old.getUserId(), "退部申请已通过");
                return Result.ok("退部申请已通过");
            } else {
                old.setState(1);
                updateById(old);
                messageService.sendMessage(old.getUserId(), "退部申请未通过");
                return Result.ok("退部申请已拒绝");
            }
        } else {
            return Result.fail("该申请不存在");
        }
    }

    @Override
    public Result deleteMySocietyMember(Long id) {
        Societies soMasterId = (Societies) societiesService.querySocietiesDetailByMasterId().getData();
        SocietiesMember old = getById(id);
        if (Objects.equals(old.getSocietiesId(), soMasterId.getSoId()) && old.getState() == 1) {
            removeById(id);
            societiesService.saveSocieties2Redis(SOCIETIES_LIST_TTL);
            messageService.sendMessage(old.getUserId(), "你已被踢出该部门");
            return Result.ok("已将该同学踢出");
        }
        return Result.fail("该成员不存在");
    }

    @Override
    public Result queryMySocietyList(Integer state) {
        Long userId;
        try {
            userId = UserHolder.getUser().getUserid();
        } catch (Exception e) {
            return Result.fail("用户未登录");
        }
        List<SocietiesMember> list = query().eq("user_id", userId).eq("state", state).list();
        List<Societies> societiesList = new ArrayList<>();
        for (SocietiesMember societiesMember : list) {
            Societies societies = societiesService.getById(societiesMember.getSocietiesId());
            societiesList.add(societies);
        }
        if (list.isEmpty()) {
            return Result.fail("您没有加入任何社团成员");
        }
        return Result.ok(societiesList);
    }
}




